class Post < ActiveRecord::Base

  has_and_belongs_to_many :members, :join_table => :likes
  has_many :includes, :dependent => :destroy
  has_many :tags, :through => :includes

  after_save :generate_tags
  
  def add_tag(keyword, cardinality)
    tag = Tag.where(:content => keyword).first
    if tag.nil? then
      tag = Tag.new
      tag.content = keyword
      tag.save
    end    
    
    include = Include.where('post_id = ? and tag_id = ?',self.id,tag.id).first
    if include.nil?
      include = Include.new
      include.tag = tag
      include.post = self
      include.cardinality = cardinality
      include.save
    else
      include.cardinality = cardinality
      include.save
    end
  end
  
  def generate_tags
    clean_input
    generate_words_array
    remove_stop_words
    stem_words
    make_keywords_hash
    print_keywords_hash
    
    self.includes.clear
    @keywords_hash.each do |content,cardinality|
      add_tag content, cardinality
    end
  end
  
  private

  def clean_input
    self.content.downcase!
    self.content.gsub!(/(<[^>]*>)|\n|\t/s, '') # makni HTML tagove 
    self.content.gsub!(/[^[:alnum:] ]/, '') # makni sve znakove osim slova brojeva i razmaka
    self.content.gsub!(/ +/, ' ') # makni visestruke razmake
  end
  

  
  # generate list of all words
  def generate_words_array
    @words_array =  self.content.split(" ")
  end
  
  
  # takes stop words from a file an removes them
  def remove_stop_words
    
    stop_words = Array.new
    
    # Procitaj sve rijeci iz datoteke, odrezi \n znak i dodaj u listu
    File.open('lib/stop_words.txt').each_line{ |word| stop_words.push(word.chop) }
    
    # Makni sve rijeci s liste stop wordova
    @words_array.delete_if do |word|
      stop_words.any? { |stop_word| stop_word == word }
    end
    
  end
  
  # napravi stemove od svih rijeci
  def stem_words
    stemmer = Lingua::Stemmer.new(:language => "en")
      @words_array = @words_array.map {|word| stemmer.stem(word)}
  end
  
  # prebroji svaku rijec i napravi hash u obliku rijec => broj_ponavljanja
  def make_keywords_hash
    unique_words = @words_array.uniq
    @keywords_hash = Hash.new
    
    #prebroji svaku rijec i spremi u hash
    unique_words.each do |word|
      appearances = @words_array.find_all{|element| element == word}.size
      
      if appearances > 0
        @keywords_hash.store(word,appearances)
      end
    end
    
  end
  
   def print_keywords_hash( n = 10)
    
    @keywords_hash.sort {|a,b| b[1]<=>a[1]}.each do |key,value|
      puts "#{key}: #{value}"
      n -= 1
      break if n <= 0
    end
  end
  
end
